package com.fivestar.pmanager.web.auth;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

public class MyAccessDeniedHandlerImpl implements AccessDeniedHandler
{
    protected static final Logger logger = LoggerFactory.getLogger(MyAccessDeniedHandlerImpl.class);
    private static final String XML_HTTP_REQUEST          = "XMLHttpRequest";
    private static final String ACCESS_DENIED_HEADER_KEY  = "Access-Denied";
    private static final String X_REQUESTED_WITH_HEADER   = "x-requested-with";
    private String errorPage;

    public MyAccessDeniedHandlerImpl()
    {

    }

    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException
    {
        boolean isAjax = request.getHeader(X_REQUESTED_WITH_HEADER) != null
                && XML_HTTP_REQUEST.equalsIgnoreCase(request.getHeader(X_REQUESTED_WITH_HEADER));
        if (isAjax)
        {
            response.setHeader(ACCESS_DENIED_HEADER_KEY, "Y");
            response.sendError(403,"");
        }
        else
        {
            if(this.errorPage != null)
            {
                request.setAttribute("SPRING_SECURITY_403_EXCEPTION", accessDeniedException);
                response.setStatus(403);
                RequestDispatcher dispatcher = request.getRequestDispatcher(this.errorPage);
                dispatcher.forward(request, response);
            }
            else
            {
                response.sendError(403, accessDeniedException.getMessage());
            }
        }

    }

    public void setErrorPage(String errorPage)
    {
        if(errorPage != null && !errorPage.startsWith("/"))
        {
            throw new IllegalArgumentException("errorPage must begin with \'/\'");
        }
        else
        {
            this.errorPage = errorPage;
        }
    }
}
